import React, { useState, useEffect } from 'react';
import { Layout, Card, DatePicker, Button, Table, Row, Col, Statistic, Spin, message, Typography, Tag, Tooltip } from 'antd';
import { BarChartOutlined, CalendarOutlined, SearchOutlined } from '@ant-design/icons';
import { useAuth } from '../context/AuthContext';
import { statisticsAPI } from '../utils/api';
import { usePermissions } from '../utils/permissions';
import dayjs from 'dayjs';
import './Statistics.css';

const { Content } = Layout;
const { RangePicker } = DatePicker;
const { Title } = Typography;

const Statistics = () => {
  const [loading, setLoading] = useState(false);
  const [dateRange, setDateRange] = useState([]);
  const [overviewStats, setOverviewStats] = useState({
    total_updates: 0,
    involved_countries: 0,
    involved_companies: 0,
    accessible_codes: 0,
    date_range: {
      earliest_date: null,
      latest_date: null
    }
  });
  const [detailedStats, setDetailedStats] = useState([]);

  const { isAuthenticated, user } = useAuth();
  const { hasPermission } = usePermissions(user);

  // 延迟权限检查，确保 user 加载完成
  const canViewStatistics = user ? hasPermission('data_statistics') : false;

  // 计算默认日期范围（30天前到今天）
  const getDefaultDateRange = () => {
    const today = dayjs();
    const thirtyDaysAgo = today.subtract(7, 'day');
    return [thirtyDaysAgo, today];
  };

  // 初始化默认日期范围
  useEffect(() => {
    setDateRange(getDefaultDateRange());
  }, []);

  useEffect(() => {
    if (isAuthenticated && user && canViewStatistics) {
      fetchOverviewStatistics();
    }
  }, [isAuthenticated, user, canViewStatistics]);

  // 限制日期选择范围在一个月内，最大时间为当天
  const disabledOneMonthDate = (current, { from, type }) => {
    if (from) {
      // 如果已经选择了开始日期，限制结束日期的选择范围
      const minDate = from.subtract(1, 'month');
      const maxDate = from.add(1, 'month');
      const today = dayjs();

      switch (type) {
        case 'year':
          return current.year() < minDate.year() || current.year() > maxDate.year();

        case 'month':
          return (
            current.month() < minDate.month() ||
            current.month() > maxDate.month()
          );

        default:
          // 限制日期范围在一个月内，且不能超过今天
          const daysDiff = Math.abs(current.diff(from, 'days'));
          return daysDiff > 30 || current.isAfter(today);
      }
    }

    // 如果没有选择开始日期，限制不能选择超过30天前的日期，也不能选择超过今天的日期
    const thirtyDaysAgo = dayjs().subtract(30, 'day');
    const today = dayjs();
    return current.isBefore(thirtyDaysAgo) || current.isAfter(today);
  };

  const fetchOverviewStatistics = async () => {
    try {
      setLoading(true);
      const response = await statisticsAPI.getStatisticsOverview();
      setOverviewStats(response);
    } catch (error) {
      console.error('获取统计概览失败:', error);
      message.error('获取统计概览失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchDetailedStatistics = async () => {
    if (!dateRange || dateRange.length !== 2) {
      message.warning('请选择日期范围');
      return;
    }

    try {
      setLoading(true);
      const [startDate, endDate] = dateRange;
      const response = await statisticsAPI.getDetailedStatistics(
        startDate.format('YYYY-MM-DD'),
        endDate.format('YYYY-MM-DD')
      );
      setDetailedStats(response.code_statistics || []);
    } catch (error) {
      console.error('获取详细统计数据失败:', error);
      message.error('获取详细统计数据失败');
    } finally {
      setLoading(false);
    }
  };

  const disabledDate = (current) => {
    const today = dayjs().endOf('day'); 
    const thirtyDaysAgo = dayjs().subtract(30, 'day').startOf('day');
  
    // 禁止今天之后的日期
    if (current.isAfter(today, 'day')) {
      return true;
    }
  
    // 开始日期不能早于30天前
    return current.isBefore(thirtyDaysAgo, 'day');
  };
  
  const handleDateRangeChange = (dates) => {
    if (dates && dates.length === 2) {
      const [startDate, endDate] = dates;
      // 如果结束日期超过今天，自动设置为今天
      const today = dayjs();
      if (endDate.isAfter(today)) {
        setDateRange([startDate, today]);
        message.info('结束日期已自动调整为今天');
      } else {
        setDateRange(dates);
      }
    } else {
      setDateRange(dates);
    }
  };

  const handleSearch = () => {
    fetchDetailedStatistics();
  };

  const handleReset = () => {
    setDateRange(getDefaultDateRange());
    setDetailedStats([]);
  };

  const columns = [
    {
      title: '海关编码',
      dataIndex: 'code',
      key: 'code',
      width: 140,
      fixed: 'left',
    },
    {
      title: '更新数量',
      dataIndex: 'update_count',
      key: 'update_count',
      width: 120,
      sorter: (a, b) => a.update_count - b.update_count,
      render: (value) => (
        <span style={{ color: '#1890ff', fontWeight: 600 }}>{value}</span>
      ),
    },
    {
      title: '涉及国家',
      dataIndex: 'countries',
      key: 'countries',
      width: 220,
      render: (countries) => {
        if (!countries || countries.length === 0) {
          return <span className="no-data">无</span>;
        }
        
        // 如果只有一个国家
        if (countries.length === 1) {
          return <Tag color="blue">{countries[0]}</Tag>;
        }
        
        // 如果有多个国家，显示前几个并显示总数
        const displayCountries = countries.slice(0, 2);
        const remainingCount = countries.length - displayCountries.length;
        
        return (
          <div>
            {displayCountries.map((country, index) => (
              <Tag key={index} color="blue" style={{ marginBottom: '2px' }}>
                {country}
              </Tag>
            ))}
            {remainingCount > 0 && (
              <Tooltip title={`还有 ${remainingCount} 个国家: ${countries.slice(2).join(', ')}`}>
                <Tag color="geekblue" style={{ cursor: 'pointer' }}>
                  +{remainingCount}
                </Tag>
              </Tooltip>
            )}
          </div>
        );
      },
    },
    {
      title: '涉及公司',
      dataIndex: 'companies',
      key: 'companies',
      width: 280,
      render: (companies) => {
        if (!companies || companies.length === 0) {
          return <span className="no-data">无</span>;
        }
        
        // 如果只有一个公司
        if (companies.length === 1) {
          return <Tag color="green">{companies[0]}</Tag>;
        }
        
        // 如果有多个公司，显示前几个并显示总数
        const displayCompanies = companies.slice(0, 2);
        const remainingCount = companies.length - displayCompanies.length;
        
        return (
          <div>
            {displayCompanies.map((company, index) => (
              <Tag key={index} color="green" style={{ marginBottom: '2px' }}>
                {company}
              </Tag>
            ))}
            {remainingCount > 0 && (
              <Tooltip title={`还有 ${remainingCount} 个公司: ${companies.slice(2).join(', ')}`}>
                <Tag color="geekblue" style={{ cursor: 'pointer' }}>
                  +{remainingCount}
                </Tag>
              </Tooltip>
            )}
          </div>
        );
      },
    },
    {
      title: '数据日期范围',
      dataIndex: 'date_range',
      key: 'date_range',
      width: 200,
      render: (dateRange) => {
        if (!dateRange || (!dateRange.earliest_date && !dateRange.latest_date)) {
          return <span className="no-data">无</span>;
        }
        
        const formatDate = (dateStr) => {
          if (!dateStr) return '无';
          try {
            return dayjs(dateStr).format('YYYY-MM-DD');
          } catch (e) {
            return dateStr;
          }
        };
        
        return (
          <div style={{ fontSize: '12px', lineHeight: '1.4' }}>
            <div style={{ color: '#28a745', fontWeight: 500 }}>
              {formatDate(dateRange.earliest_date)}
            </div>
            <div style={{ color: '#6c757d', margin: '2px 0' }}>至</div>
            <div style={{ color: '#dc3545', fontWeight: 500 }}>
              {formatDate(dateRange.latest_date)}
            </div>
          </div>
        );
      },
    },
  ];

  // 权限检查逻辑
  if (!isAuthenticated) {
    return (
      <Layout>
        <Content style={{ padding: '50px', textAlign: 'center' }}>
          <h2>请先登录</h2>
          <p>您需要登录后才能访问数据统计功能</p>
        </Content>
      </Layout>
    );
  }

  if (!user) {
    return (
      <Layout>
        <Content style={{ padding: '50px', textAlign: 'center' }}>
          <h2>加载中...</h2>
          <p>正在加载用户信息，请稍候</p>
        </Content>
      </Layout>
    );
  }

  if (!canViewStatistics) {
    return (
      <Layout>
        <Content style={{ padding: '50px', textAlign: 'center' }}>
          <h2>权限不足</h2>
          <p>您没有访问数据统计的权限</p>
        </Content>
      </Layout>
    );
  }

  return (
    <Layout>
      <Content style={{ padding: '24px' }}>
        <div className="statistics-page">
          <div className="page-header">
            <h1>
              <BarChartOutlined /> 数据统计
            </h1>
            <p>查看海关数据的详细统计信息（仅限最近30天，结束日期为今天）</p>
          </div>

          {/* 概览统计 */}
          <Card title="昨天统计概览" className="overview-card">
            <Row gutter={[12, 12]}>
              <Col xs={24} sm={12} lg={4}>
                <Statistic
                  title="更新数据"
                  value={overviewStats.total_updates}
                  prefix={<BarChartOutlined />}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Col>
              <Col xs={24} sm={12} lg={4}>
                <Statistic
                  title="涉及国家"
                  value={overviewStats.involved_countries}
                  prefix={<CalendarOutlined />}
                  valueStyle={{ color: '#52c41a' }}
                />
              </Col>
              <Col xs={24} sm={12} lg={4}>
                <Statistic
                  title="涉及公司"
                  value={overviewStats.involved_companies}
                  prefix={<CalendarOutlined />}
                  valueStyle={{ color: '#722ed1' }}
                />
              </Col>
              <Col xs={24} sm={12} lg={4}>
                <Statistic
                  title="可访问编码"
                  value={overviewStats.accessible_codes}
                  prefix={<CalendarOutlined />}
                  valueStyle={{ color: '#fa8c16' }}
                />
              </Col>
              
              {/* 日期范围统计 */}
              <Col xs={24} sm={12} lg={8}>
                <Statistic
                  title="数据日期范围"
                  value={overviewStats.date_range && overviewStats.date_range.earliest_date && overviewStats.date_range.latest_date 
                    ? `${overviewStats.date_range.earliest_date} ~ ${overviewStats.date_range.latest_date}`
                    : '无'
                  }
                  prefix={<CalendarOutlined />}
                  valueStyle={{ 
                    color: '#1890ff'
                  }}
                />
              </Col>
            </Row>
          </Card>

          {/* 详细统计 */}
          <Card title="详细统计" className="detailed-card">
            <div className="search-section">
              <Title level={5}>30天内日期范围（结束日期为今天）</Title>
              <Row gutter={[16, 16]} align="middle">
                <Col>
                  <span className="search-label">选择日期范围：</span>
                </Col>
                <Col>
                <RangePicker
                    value={dateRange}
                    onChange={handleDateRangeChange}
                    format="YYYY-MM-DD"
                    placeholder={['开始日期', '结束日期']}
                    style={{ width: 280 }}
                    disabledDate={disabledDate}
                    />
                </Col>
                <Col>
                  <Button
                    type="primary"
                    icon={<SearchOutlined />}
                    onClick={handleSearch}
                    loading={loading}
                  >
                    查询统计
                  </Button>
                </Col>
                <Col>
                  <Button
                    icon={<CalendarOutlined />}
                    onClick={handleReset}
                  >
                    重置
                  </Button>
                </Col>
              </Row>
              <div style={{ marginTop: '8px', color: '#8c8c8c', fontSize: '12px' }}>
                提示：只能选择最近30天内的日期范围，结束日期不能超过今天，最大时间范围为30天
              </div>
            </div>

            <div className="table-section">
              <Table
                columns={columns}
                dataSource={detailedStats}
                rowKey="code"
                loading={loading}
                pagination={{
                  pageSize: 20,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  showTotal: (total) => `共 ${total} 条记录`,
                }}
                scroll={{ x: 1150 }}
                size="middle"
              />
            </div>
          </Card>
        </div>
      </Content>
    </Layout>
  );
};

export default Statistics;